package com.lx.zy.framework.security.handle;

import com.alibaba.fastjson.JSON;
import com.lx.zy.common.constant.HttpStatus;
import com.lx.zy.common.utils.ServletUtils;
import com.lx.zy.common.utils.StringUtils;
import com.lx.zy.framework.web.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * @program: zy-vue
 * @description: 认证失败处理类 返回未授权
 * @author: Lx
 * @create: 2019-10-18 23:03
 **/
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
{

    private static final long serialVersionUID = -7471699584628332006L;

    private static final Logger logger = LoggerFactory.getLogger(AuthenticationEntryPointImpl.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException
    {
        int code = HttpStatus.UNAUTHORIZED;
        String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        logger.debug("【request.getRequestURI()】:{}", request.getRequestURI());
        logger.debug("【msg】:{}", msg);
        logger.debug("【AjaxResult.error】:{}", JSON.toJSONString(AjaxResult.error(code, msg)));
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
    }
}
